<template>
  <div class="dashboard-container">
    <div class="app-container new-questions">
       <el-card shadow="never">
         <!-- 标题 -->
         <div slot="header" class="clearfix">
          <span>{{ functionTitle }}</span>
        </div>
        <!-- 表单项数据 -->
        <el-form ref="form" :model="form" label-width="100px" :rules="rules">
          <!-- 学科 -->
          <el-form-item label="学科" prop="subjectID">
              <el-select v-model="form.subjectID" placeholder="请选择" style="width:400px" @change="handleSubjectChange">
                <el-option v-for="item in subjects" :key="item.value"  :label="item.label" :value="item.value"></el-option>
              </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录" prop="catalogID">
              <el-select v-model="form.catalogID" placeholder="请选择"  style="width:400px">
                <el-option v-for="item in directorys" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业" prop="enterpriseID">
              <el-select v-model="form.enterpriseID" placeholder="请选择"  style="width:400px">
                <el-option v-for="item in companys" :key="item.id" :label="item.shortName" :value="item.id"></el-option>
              </el-select>
          </el-form-item>
          <!-- 城市 -->
          <div class="address">
            <el-form-item label="城市" prop="province">
              <!-- 省 -->
              <el-select v-model="form.province" placeholder="请选择" style="width:195px; margin-right:10px" @change="handleProvinceChange">
                <el-option v-for="(item, index) in provinces" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="city" prop="city">
              <!-- 市 -->
              <el-select v-model="form.city" placeholder="请选择" style="width:195px">
                <el-option v-for="(item, index) in citys" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 方向 -->
          <el-form-item label="方向" prop="direction">
           <el-col :span="11">
              <el-select v-model="form.direction" placeholder="请选择" style="width:400px">
                <el-option v-for="(item, index) in direction" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型" prop="questionType">
            <el-radio-group v-model="form.questionType">
              <el-radio v-for="(item, index) in questionType" :key="index" :label="String(item.value)">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度" prop="difficulty">
            <el-radio-group v-model="form.difficulty">
              <el-radio v-for="(item, index) in difficulty" :key="index" :label="String(item.value)">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干" v-model="form.question" prop="question">
            <quill-editor v-model="form.question" :options="editorOption" />
          </el-form-item>
          <!-- 单选选项 -->
          <el-form-item label="选项" v-if="form.questionType === '1'" prop="option">
            <el-radio-group v-model="option" style="width:400px">
              <!-- 引入子组件,显示单选选项 -->
              <custom-option v-for="(item, index) in radioOptions" :key="index" :questionType="form.questionType" v-model="radioOptions[index]"></custom-option>
            </el-radio-group>
          </el-form-item>
          <!-- 多选选项 -->
          <el-form-item label="选项" v-if="form.questionType === '2'" prop="option">
            <el-checkbox-group v-model="checkOption" style="width:400px">
              <!-- 引入子组件,显示选项 -->
              <custom-option v-for="(item, index) in checkboxOptions" :key="item.code" :idx="index" :questionType="form.questionType" v-model="checkboxOptions[index]" @deloption="handleDelOption(index)">
              </custom-option>
            </el-checkbox-group>
            <el-button type="primary" @click="handleAddOption">+增加选项与答案</el-button>
            <el-button type="danger" @click="handleDelLastOption" :disabled="checkboxOptions.length <= 4 ? true : false"><i class="el-icon-delete"></i>删除最后一项</el-button>
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频" prop="videoURL">
            <el-input v-model="form.videoURL" style="width:400px"></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析" prop="answer">
            <quill-editor v-model="form.answer" :options="editorOption"/>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注" prop="remarks">
            <el-input type="textarea" v-model="form.remarks" style="width:400px"></el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签" prop="tags">
            <el-select v-model="form.tags" multiple style="width:400px" placeholder="请选择">
              <el-option v-for="(item, index) in tags" :key="index" :label="item.label" :value="item.label"></el-option>
            </el-select>
          </el-form-item>
          <!-- 提交/修改按钮 -->
          <el-form-item>
            <el-button type="success" :loading="loading" @click="handleSubmit" v-if="$route.query && Object.keys($route.query).length > 0">确认修改</el-button>
            <el-button type="primary" :loading="loading" @click="handleSubmit" v-else>确认提交</el-button>
          </el-form-item>
        </el-form>
       </el-card>
    </div>
  </div>
</template>

<script>
// 导入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 导入组件
import { quillEditor } from 'vue-quill-editor'
import CustomOption from '@/module-hmmm/components/questions-option'
// 导入方法
import { simple as getSubjectSimple } from '@/api/hmmm/subjects.js'
import { simple as getDirectorySimple } from '@/api/hmmm/directorys.js'
import { simple as getTagSimple } from '@/api/hmmm/tags.js'
import { list as getCompanyList } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction, difficulty, questionType } from '@/api/hmmm/constants'
import { add as addQuestion, detail, update } from '@/api/hmmm/questions.js'

export default {
  name: 'question-new',
  components: {
    quillEditor,
    CustomOption
  },
  data () {
    return {
      loading: false,
      defaultOptionNum: 4,
      subjects: [], // 学科列表
      directorys: [], // 目录列表
      tags: [], // 标签列表
      companys: [], // 企业列表
      provinces: [], // 省列表
      citys: [], // 市列表
      option: '', // 单选选中项
      checkOption: [], // 多选选中项
      radioOptions: [], // 单选选项
      checkboxOptions: [], // 多选选项
      form: { // 表单绑定数据
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: null, // 省
        city: null, // 省
        direction: null, // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        remarks: '', // 备注
        options: [], // 选项
        videoURL: '', // 视频
        answer: '', // 答案
        tags: [] // 标签
      },
      rules: { // 验证规则
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择省', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请选择标签', trigger: ['change', 'blur'] }
        ]
      },
      editorOption: {
        // 占位配置
        placeholder: '',
        modules: {
          // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      }
    }
  },
  computed: {
    direction () {
      return direction
    },
    difficulty () {
      return difficulty
    },
    questionType () {
      return questionType
    },
    // 判断是否为编辑页面
    isEdit () {
      return Object.keys(this.$route.query).length > 0
    },
    functionTitle () {
      return this.isEdit ? '试题修改' : '试题录入'
    }
  },
  created () {
    this.initData() // 初始化表单数据
  },
  methods: {
    // 页面加载时初始化页面数据
    initData () {
      this.doGetSubjectSimple() // 初始化学科列表
      this.doGetCompanyList() // 初始化企业列表
      this.doGetProvinceData() // 初始化省列表
      this.initOption(this.defaultOptionNum) // 初始化选项
      // 如果是试题编辑,获取试题信息
      const { id } = this.$route.query
      if (id) {
        this.doGetDetail(id)
      }
    },

    // 试题编辑-获取试题信息
    async doGetDetail (questionId) {
      try {
        const res = await detail({ id: questionId })
        const {
          id,
          subjectID,
          catalogID,
          enterpriseID,
          province,
          city,
          direction,
          questionType,
          difficulty,
          question,
          remarks,
          options,
          videoURL,
          answer,
          tags
        } = res.data
        this.form = {
          id,
          subjectID,
          catalogID,
          enterpriseID,
          province,
          city,
          options,
          direction,
          questionType,
          difficulty,
          question,
          remarks,
          videoURL,
          answer,
          tags
        }
        // 将获取的tag字符串转换为数组
        this.form.tags = tags ? tags.split(',') : []
        // "1"表示为单选题,初始化单选项;"2"表示为多选项,初始化多选项
        if (questionType === '1') {
          this.initRadioOption(options)
        } else if (questionType === '2') {
          this.initCheckboxOption(options)
        }
        // 根据学科id获取目录列表
        this.doGetDirectorySimple(this.form.subjectID)
        // 根据学科id获取标签列表
        this.doGetTagSimgle(this.form.subjectID)
        // 根据省获取市
        this.citys = citys(this.form.province)
      } catch (err) {
        console.log(err)
        this.$message.error('获取试题信息失败')
      }
    },

    // 试题编辑时,初始化radio选项数据,若返回isRight字段为1,标识为正确项
    initRadioOption (options) {
      this.radioOptions = options
      const idx = this.radioOptions.findIndex(item => {
        return item.isRight === 1
      })
      this.option = idx === -1 ? '' : this.radioOptions[idx].code
      // 将返回的选项按字母进行排序
      this.sortByCode(this.radioOptions)
    },

    // 试题编辑时,初始化checkbox选项数据,若返回isRight字段为1,标识为正确项
    initCheckboxOption (options) {
      this.checkboxOptions = options
      this.checkboxOptions.forEach(item => {
        if (item.isRight === 1) {
          this.checkOption.push(item.code)
        }
      })
      // 将返回的选项按字母进行排序
      this.sortByCode(this.checkboxOptions)
    },

    // 试题录入时,初始化选项数据(包含单选及多选)
    initOption (num) {
      let codeASCII = 65
      for (var i = 0; i < num; i++ ) {
        let obj = {
          isRight: false,
          code: String.fromCharCode(codeASCII),
          title: '',
          img: ''
        }
        this.radioOptions.push({ ...obj })
        this.checkboxOptions.push({ ...obj })
        codeASCII++
      }
    },

    // 构建请求参数
    buildParams () {
      const params = Object.assign({}, this.form)
      // 提交时修改tags数组为接口需要的字符串
      params.tags = params.tags ? params.tags.join(',') : null
      // "1"表示单选题,"2"标识多选题,设置正确项的isRight字段为true(简答题不存在选项)
      if (params.questionType === '1') {
        this.radioOptions.forEach((item, index) => {
          this.radioOptions[index].isRight = item.code === this.option
        })
        params.options = this.radioOptions
      } else if (params.questionType === '2') {
        this.checkboxOptions.forEach((item, index) => {
          this.checkboxOptions[index].isRight = this.checkOption.includes(item.code)
        })
        params.options = this.checkboxOptions
      } else {
        params.options = []
      }
      // 去除解析视频/题目备注文本框前后空格
      params.videoURL = params.videoURL.trim()
      params.remarks = params.remarks.trim()
      // 去除选项标题前后空格
      params.options.forEach(obj => {
        obj.title = obj.title.trim()
      })
      return params
    },

    // ajax请求录入数据
    async doAddQuestion (params) {
      this.loading = true
      try {
        await addQuestion(params)
        this.$message.success('试题录入成功!')
        this.$router.push('/questions/list')
        this.loading = false
      } catch (err) {
        console.log(err)
        this.$message.error('试题录入失败!')
        this.loading = false
      }
    },

    // ajax请求修改试题
    async doEditQuestion (params) {
      this.loading = true
      try {
        await update(params)
        this.$message.success('试题修改成功!')
        // 跳转至基础题库
        this.$router.push('/questions/list')
        this.loading = false
      } catch (err) {
        console.log(err)
        this.$message.error('试题修改失败!')
        this.loading = false
      }
    },

    // 提交录入或者修改试题
    handleSubmit () {
      this.$refs.form.validate((valid) => {
        // 若表单验证不通过,直接返回
        if (!valid) {
          this.$message.error('*为必填项')
          return
        }
        // 验证表单是否选择了正确选项
        if (this.form.questionType === '1' && !this.option || this.form.questionType === '2' && this.checkOption.length === 0) {
          this.$message.warning('请选择正确项')
          return
        }
        // 如果是编辑页面解析视频/题目备注验证不可为空
        if (this.isEdit) {
          if (!this.form.videoURL.trim()) {
            this.$message.warning('试题编辑,视频不可为空或空字符串')
            return
          }
          if (!this.form.remarks.trim()) {
            this.$message.warning('试题编辑,题目备注不可为空或空字符串')
            return
          }
        }
        // 构建请求参数,如果是编辑,执行试题编辑;如果是录入,执行试题录入
        const params = this.buildParams()
        if (this.isEdit) {
          this.doEditQuestion(params)
        } else {
          this.doAddQuestion(params)
        }
      })
    },

    // 获取学科列表
    async doGetSubjectSimple () {
      try {
        const res = await getSubjectSimple()
        this.subjects = res.data
      } catch (err) {
        console.log(err)
        this.$message.error('获取学科列表失败!')
      }
    },

    // 获取企业列表
    async doGetCompanyList () {
      try {
        const res = await getCompanyList()
        this.companys = res.data.items
      } catch (err) {
        console.log(err)
        this.$message.error('获取企业列表失败!')
      }
    },

    // ajax请求获取目录数据
    async doGetDirectorySimple (subjectID) {
      try {   
        const res = await getDirectorySimple({ subjectID: subjectID })
        this.directorys = res.data
      } catch (err) {
        console.log(err)
        this.$message.error('目录数据获取失败!')
      }
    },

    // ajax请求获取tags列表数据
    async doGetTagSimgle (subjectID) {
      try {
        const res = await getTagSimple({ subjectID: subjectID })
        this.tags = res.data
      } catch (err) {
        console.log(err)
        this.$message.error('标签数据获取失败!')
      }
    },

    // 改变学科项-获取目录列表和tags,并设置默认为空
    handleSubjectChange () {
      this.doGetDirectorySimple(this.form.subjectID)
      this.doGetTagSimgle(this.form.subjectID)
      this.form.catalogID = null
      this.form.tags = []
    },

    // 获取省列表
    doGetProvinceData () {
      this.provinces = provinces()
    },

    // 省改变时-获取市列表
    handleProvinceChange (province) {
      this.citys = citys(province)
      this.form.city = this.citys[0]
    },

    // 点击新增选项与答案解析(选项范围为A-Z)
    handleAddOption () {
      let code = this.checkboxOptions[this.checkboxOptions.length - 1].code
      const codeASCII = code.charCodeAt()
      if (codeASCII < 90) {
        code = String.fromCharCode(codeASCII + 1)
        const optionObj = {
          isRight: false,
          code: code,
          title: '',
          img: ''
        }
        this.checkboxOptions.push(optionObj)
      } else {
        this.$message.warning('选项可用范围为A-Z')
      }
    },

    // 点击删除复选框答案最后一项
    handleDelLastOption () {
      this.checkboxOptions.pop()
    },

    // 删除复选框某个选项并重置选项序号
    handleDelOption (idx) {
      this.checkboxOptions.splice(idx, 1)
      var firstCodeNum = 65 // A的ASCII编码
      this.checkboxOptions.forEach((item, index) => {
        this.checkboxOptions[index].code = String.fromCharCode(firstCodeNum + index)
      })
    },

    // 对选项按字母进行排序
    sortByCode (options) {
      return options.sort((optionA, optionB) => {
        const codeA = optionA.code
        const codeB = optionB.code
        if (codeA < codeB) {
          return -1
        } else if (codeA > codeB) {
          return 1
        } else {
          return 0
        }
      })
    },

    // 清空表单项相关数据
    clearFormData () {
      this.$refs.form.resetFields()
      this.citys = []
      this.directorys = []
      this.tags = []
      this.companys = []
      this.provinces = []
      this.radioOptions = []
      this.checkboxOptions = []
      this.option = ''
      this.checkOption = []
    }
  },
  watch: {
    // 监听路由变化,重新加载组件数据
    '$route' (to, from) {
      if (to.query !== from.query) {
        // 清除表单项相关数据
        this.clearFormData()
        // 重新加载组件数据
        this.initData()
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.new-questions ::v-deep .ql-editor {
  height: 200px;
}
.options {
  margin-top: 10px;
}
.address {
  position: relative;
}
.city {
  position: absolute;
  top: 0;
  left: 307px;
}
.city ::v-deep .el-form-item__content {
  margin-left: 0 !important;
}
</style>
